package com.watson.tool.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.watson.tool.message.MessageProducer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.websocket.Session;
import java.io.IOException;
import java.util.Map;

/**
 * @Deacription  websocket工具类
 **/
@Component
@Slf4j
public class WebsocketUtils implements ApplicationContextAware {
    
    private ApplicationContext ctx;

    private MessageProducer messageProducer;

    @Value("${iot.websocket.notify.topic:WebSocketNotify}")
    private String webSocketNotifyTopic;

    /**
     * 发送信息给前端
     * @param dataType
     * @param dataId
     * @param msg
     */
    public void sendBrowserMessage(String dataType, String dataId,
            JSONObject msg) {
        sendMessage("browser", null, dataType, dataId, msg);
    }

    /**
     * 发送信息给前端
     * @param clientGroup
     * @param userCode
     * @param dataType
     * @param dataId
     * @param msg
     */
    public void sendMessage(String clientGroup, String userCode, String dataType, String dataId,
            JSONObject msg) {
        JSONObject packet = new JSONObject();
        packet.put("clientGroup", clientGroup);
        packet.put("userCode", userCode);
        packet.put("dataType", dataType);
        packet.put("dataId", dataId);
        packet.put("msg", msg);
        getMessageProducer().sendMessage(webSocketNotifyTopic, packet.toString());
    }

    public void sendMessageArr(String clientGroup, String userCode, String dataType, String dataId,
                            JSONArray arr) {
        JSONObject packet = new JSONObject();
        packet.put("clientGroup", clientGroup);
        packet.put("userCode", userCode);
        packet.put("dataType", dataType);
        packet.put("dataId", dataId);
        packet.put("msg", arr);
        getMessageProducer().sendMessage(webSocketNotifyTopic, packet.toString());
    }
	
    /**
     * 根据传入的map关闭session
     * @param sessionMap
     * @param key
     */
    public static void closeSession(Map<String, Session> sessionMap, String key){
        Session session = sessionMap.get(key);
        if(null != session){
            try {
                session.close();
                //删除map中的项
                sessionMap.remove(key);
            } catch (IOException e) {
                log.error("关闭websocket的session出现异常,msg:" + e.getMessage());
                e.printStackTrace();
            }
        }
    }

    /**
     * websocket单发消息
     * @param sessionMap session的map
     * @param key key
     * @param message 数据
     */
    public static void sendSingleMessage(Map<String, Session> sessionMap,String key,String message){
        try {
            sessionMap.get(key).getAsyncRemote().sendText(message);
            log.info("websocket发送消息,key:" + key + ",消息:" + message);
        }catch (Exception ex){
            log.error("websocket发送消息出现异常,key:" + key + ",消息:" + message,ex);
            ex.printStackTrace();
        }

    }

    /**
     * websocket群发消息
     * @param sessionMap
     * @param message
     */
    public static boolean sendGroupMessage(Map<String, Session> sessionMap,String message){
        try {
            if (!sessionMap.isEmpty()) {
                for (String temp : sessionMap.keySet()) {
                    sessionMap.get(temp).getAsyncRemote().sendText(message);
                }
                return true;
            }else{
                return false;
            }
        }catch (Exception ex){
            log.error("websocket群发消息出现异常",ex);
            ex.printStackTrace();
            return false;
        }
    }
	
    private MessageProducer getMessageProducer() {
        if(messageProducer == null){
            if(ctx != null){
                Map<String, MessageProducer> producers = ctx.getBeansOfType(MessageProducer.class);
                if(producers != null && producers.size() > 0){
                    messageProducer = producers.values().iterator().next();
                }
            }
        }
        return messageProducer;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.ctx = applicationContext;
    }
}
